package com.jinzheng.qhwocket.util.testDiaoyongSocket;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TestDiaoyongSocketClient {

    public JSONObject testRequest(String userCode,String ip,int port) throws IOException {
        Socket socket = new Socket(ip, port);
        OutputStream os = socket.getOutputStream();
        byte[] param = byteMergerAll(
                fillParam("210", 3),//交易码
                fillParam(userCode, 10));//用户代码
        os.write(param);
        InputStream is = socket.getInputStream();
        byte[] result = new byte[1024];
        is.read(result);
        log.info("响应信息:{},{}",new String(result, "GBK"));
        JSONObject resultJSON = new JSONObject();
        resultJSON.put("businessCode", new String(getByteByIndex(result, 0, 3)));//交易码
        resultJSON.put("code", new String(getByteByIndex(result, 4, 6)).trim());//响应码
        return resultJSON;
    }

    /**
     * 合并多个byte数组
     *
     * @param values
     * @return
     */
    private byte[] byteMergerAll(byte[]... values) {
        int length_byte = 0;
        for (int i = 0; i < values.length; i++) {
            length_byte += values[i].length;
        }
        byte[] all_byte = new byte[length_byte];
        int countLength = 0;
        for (int i = 0; i < values.length; i++) {
            byte[] b = values[i];
            System.arraycopy(b, 0, all_byte, countLength, b.length);
            countLength += b.length;
        }
        return all_byte;
    }

    /**
     * 格式化参数
     *
     * @param str
     * @param count
     * @return
     */
    private byte[] fillParam(String str, int count) throws UnsupportedEncodingException {
        if (str.getBytes("GBK").length >= count) {
            return str.getBytes("GBK");
        }
        byte[] data = str.getBytes("GBK");
        byte[] empty = new byte[count - data.length];
        for (int i = 0; i < empty.length; i++) {
            empty[i] = 32;
        }
        return byteMergerAll(empty, data);
    }

    /**
     * 截取数组
     *
     * @param original
     * @param begin
     * @param end
     * @return
     */
    private byte[] getByteByIndex(byte[] original, int begin, int end) {
        byte[] result = new byte[end - begin + 1];
        int j = 0;
        for (int i = begin; i <= end; i++) {
            result[j] = original[i];
            j++;
        }
        return result;
    }


}
